package org.yuezejian.alarm.netty.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * UDPClientHandler
 * 用于处理消息和事件(可以自定义多个handler处理不同的消息事件，默认使用父类的重试机制),新增自定义Handler需要在spring配置文件中注册
 *
 * @author yuezejian
 * @since 2024.8.1
 */
@Component("clientUDPHandler")
@ChannelHandler.Sharable
@Slf4j
public class ClientUDPHandler extends AbstractClientHandler {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        // 处理接收到的消息
        log.info("MyCustomHandler received message: " + msg);

        // 这里可以添加针对特定消息类型的处理逻辑
        if (msg.equals("HEARTBEAT_ACK")) {
            log.info("Heartbeat acknowledged by server.");
        } else {
            // 其他消息处理逻辑
            //处理实际业务
            String message = msg.toString();
            InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
            String clientIP = insocket.getAddress().getHostAddress();
            int port = insocket.getPort();
            String ip = clientIP + ":" + port;
            log.error(ip+" , 接收到信息 : " + message);
            log.info("channelRead0 接收到了消息 end");
        }
    }
    @Override
    protected boolean shouldReconnect(ChannelHandlerContext ctx) {
        // 自定义重连决策逻辑
        // 例如，可以根据接收到的消息或其他条件决定是否重连
        return super.shouldReconnect(ctx); // 默认情况下重连
    }

}
